<template>
	<s-table ref='table' size='default' rowKey='id' :columns='columns' :data='data' showPagination='auto'
		:pagination='pagination'>
		<template slot='img_url' slot-scope='text'>
			<a-avatar shape='square' :size='64' icon='skin' :src='text' />
		</template>
		<a-badge :status='orderStatus(record.status)' :text='record | statusFilter' slot='status'
			slot-scope='text, record' />
		<template slot='is_offline' slot-scope='text,record'>
			<a-tag v-if='text === 1' color='cyan'>线下</a-tag>
			<a-tag v-else color='blue'>线上</a-tag>
		</template>
		<span slot='action' slot-scope='text, record'>
			<a @click='handleEdit(record)'>详情</a>
			<!-- <a @click='handleEdit(record)' style="margin: 10px" v-if="record.express_status != 1">物流打印</a> -->
			<a @click='printWL(record)' style="margin: 10px" v-if="record.is_take == '10' && record.is_offline =='0' && record.is_self== '0'">发快递</a>
			<a @click='finishOrder(record)' style="margin: 10px" v-if="record.is_take == '10'">确认完成</a>
			<a @click='cancelWL(record)' style="margin: 10px" v-if="record.express_status == 1 && record.is_take == '14'">取消物流</a>
			<a @click='printOrder(record)' style="margin: 10px" v-if="record.express_status == 1">打印面单</a>
			<a @click='handleEdit(record)' style="margin: 10px"
				v-if="userInfo.type === 3&&record.status === 1 && record.is_take<8">分拣</a>
			<!-- <template
				v-if='record.is_offline === 1 && record.status === 1 && record.is_take === 10 && record.steward_user_id==0'>
				<a-divider type='vertical'></a-divider>
				<a @click='handleConfirm(record)'>确认完成</a>
			</template> -->
			<template v-if='record.is_offline === 1 && record.status === 1 && record.is_take <= 6'>
				<a-divider type='vertical'></a-divider>
				<a @click='handleRefund(record)'>退款</a>
			</template>
		</span>
	</s-table>
</template>

<script>
	import formTableMixin from '@/mixins/formTableMixin'
	import orderStatus from '@/mixins/orderStatus'
	import {
		clothesConfirm,
		clothesRefund,
		toExpress,
		cannelExpress,
		orderInfo
	} from '@/api/clothes'
	import {
		mapGetters
	} from "vuex";

	const columns = [{
			title: 'ID',
			dataIndex: 'id',
		},
		{
			title: '姓名',
			dataIndex: 'take_name',
		},
		{
			title: '手机号',
			dataIndex: 'take_mobile'
		},
		{
			title: '支付价格',
			dataIndex: 'price',
			customRender(text) {
				return '￥' + text
			}
		},
		// {
		//   title: '服务地址',
		//   dataIndex: 'take_address'
		// },
		{
			title: '线上/线下',
			dataIndex: 'is_offline',
			scopedSlots: {
				customRender: 'is_offline'
			}
		},
		{
			title: '身份',
			dataIndex: 'idcard',
			customRender(_, record) {
				let cardShow = []
				if (record.is_vip === 1 && record.is_steward === 1) {
					cardShow.push('V·L')
				} else if (record.is_vip === 1) {
					cardShow.push('V')
				} else if (record.is_steward === 1) {
					cardShow.push('L')
				}
				if (!cardShow.length) cardShow.push('-')
				return cardShow.join(' ')
			}
		},
		// {
		// 	title: '封签码',
		// 	dataIndex: 'seal_code'
		// },
		{
			title: '订单号',
			dataIndex: 'out_trade_no'
		},
		{
			title: '时间',
			dataIndex: 'ctime',
		},
		{
			title: '状态',
			dataIndex: 'status',
			scopedSlots: {
				customRender: 'status'
			}
		},
		{
			title: '操作',
			dataIndex: 'action',
			scopedSlots: {
				customRender: 'action'
			}
		}
	]
	export default {
		mixins: [orderStatus, formTableMixin],
		props: {
			data: {
				type: Function,
				required: true
			}
		},
		data() {
			return {
				columns:[],
				lockReconnect:false, //是否真正建立连接
				timeout: 58 * 1000, //58秒一次心跳
				timeoutObj: null, //心跳心跳倒计时
				serverTimeoutObj: null, //心跳倒计时
				timeoutnum: null, //断开 重连倒计时
				formatDate:'',
				printerList:[],//打印机list
				printName:'',//打印机名称
			}
		},
		created(){
			this.columns = columns;
			this.initWebSocket();
		},
		// 销毁定时器
		beforeDestroy() {
			if (this.formatDate) {
				clearInterval(this.formatDate); // 在Vue实例销毁前，清除时间定时器
			}
		},
		destroyed() {
			this.websock.close(); //离开路由之后断开websocket连接
		},
		computed: {
			...mapGetters(['userInfo'])
		},
		methods: {
			// 完成订单
			finishOrder(order){
				this.$confirm({
					title: '提示',
					content: '确认该订单已完结？',
					onOk: () => clothesConfirm({
						id: order.id
					}).then(res => {
						this.$message.success(res.msg)
						this.handleSearch();
						return res.data
					}).catch(err => err)
				})
			},
			currentTime() {
				setInterval(this.formatDate, 500);
			},
			initWebSocket(e) {
				//初始化weosocket
				const wsuri = "ws://localhost:9113";
				this.websock = new WebSocket(wsuri);
				// 客户端接收服务端数据时触发
				this.websock.onmessage = this.websocketonmessage;
				// 连接建立时触发
				this.websock.onopen = this.websocketonopen;
				// 通信发生错误时触发
				this.websock.onerror = this.websocketonerror;
				// 连接关闭时触发
				this.websock.onclose = this.websocketclose;
			},
			// 连接建立时触发
			websocketonopen(e) {
				//开启心跳
				this.start();
				//连接建立之后执行send方法发送数据
				// let actions = {"room":"007854ce7b93476487c7ca8826d17eba","info":"1121212"};
				// this.websocketsend(JSON.stringify(actions));
			},
			// 通信发生错误时触发
			websocketonerror() {
				console.log("出现错误");
				this.reconnect();
			},
			// 客户端接收服务端数据时触发
			websocketonmessage(e) {
				var json = eval('(' + e.data + ')');
				var content = json.content;
				// alert('打印机列表:'+content);
				this.printerList = json.content.split(',');
				this.printerList.forEach((item,index)=>{
					let idx = item.indexOf('Deli');
					if(idx != '-1'){
						this.printName = item;
					}
				})
				// this.printName = this.printerList.find((item,index)=>{return item.indexOf('Deli') != '-1'});
				//收到服务器信息，心跳重置
				this.reset();
			},
			websocketsend(Data) {
				//数据发送
				this.websock.send(Data);
			},
			// 连接关闭时触发
			websocketclose(e) {
				//关闭
				console.log("断开连接", e);
				//重连
				this.reconnect();
			},
			reconnect() {
				//重新连接
				var that = this;
				if (that.lockReconnect) {
					return;
				}
				that.lockReconnect = true;
				//没连接上会一直重连，设置延迟避免请求过多
				that.timeoutnum && clearTimeout(that.timeoutnum);
				that.timeoutnum = setTimeout(function () {
					//新连接
					that.initWebSocket();
					that.lockReconnect = false;
				}, 5000);
			},
			reset() {
				//重置心跳
				var that = this;
				//清除时间
				clearTimeout(that.timeoutObj);
				clearTimeout(that.serverTimeoutObj);
				//重启心跳
				that.start();
			},
			start(e) {
				//开启心跳
				console.log("开启心跳");
				var self = this;
				self.timeoutObj && clearTimeout(self.timeoutObj);
				self.serverTimeoutObj && clearTimeout(self.serverTimeoutObj);
				self.timeoutObj = setTimeout(function () {
					//这里发送一个心跳，后端收到后，返回一个心跳消息，
					if (self.ws.readyState == 1) {
						//如果连接正常
						// self.ws.send("heartCheck"); //这里可以自己跟后端约定
					} else {
						//否则重连
						self.reconnect();
					}
					self.serverTimeoutObj = setTimeout(function () {
						//超时关闭
						self.ws.close();
					}, self.timeout);
				}, self.timeout);
			},
			// 打印面单
			printOrder(record){
				let time = 0;
				let timer = setInterval(()=>{
					var text = "{\"orderType\":\"GET_Printers\",\"pin\":\"用户名\",\"parameters\":{		\"tempUrl\":\"\",		\"printName\":\"\",		\"printData\":\"\"	}}";
					this.websocketsend(text);
					time++;
					if(this.printName){
						clearInterval(timer);
						orderInfo({
							id: record.id
						}).then(res=>{
							if (res.status == '0') {
								if(this.printName){
									res.data.parameters.printName = this.printName;
								}
								this.websocketsend(JSON.stringify({
									orderType:res.data.orderType,
									key:res.data.key,
									parameters:res.data.parameters,
								}));
							} else {
								this.$message.error(res.msg);
							}
						})
					}else{
						if(time >= 5){
							clearInterval(timer);
							this.$message.error('请检查打印设备并重试');
						}
					}
				},1000);
			},
			// 打印物流
			printWL(record){
				// alert('打印机名称：'+this.printName);
				let time = 0;
				let timer = setInterval(()=>{
					var text = "{\"orderType\":\"GET_Printers\",\"pin\":\"用户名\",\"parameters\":{		\"tempUrl\":\"\",		\"printName\":\"\",		\"printData\":\"\"	}}";
					this.websocketsend(text);
					time++;
					if(this.printName){
						clearInterval(timer);
						toExpress({
							id: record.id 
						}).then(res=>{
							if (res.status == '0') {
								if(this.printName){
									res.data.parameters.printName = this.printName;
								}
								this.websocketsend(JSON.stringify({
									orderType:res.data.orderType,
									key:res.data.key,
									parameters:res.data.parameters,
								}));
							} else {
								this.$message.error(res.msg);
							}
						})
					}else{
						if(time >= 5){
							clearInterval(timer);
							this.$message.error('请检查打印设备并重试');
						}
					}
				},1000);
			},
			// 取消物流
			cancelWL(record){
				cannelExpress({
					id: record.id
				}).then(res=>{
					if (res.status == '0') {
						window.location.reload();
					} else {
						this.$message.error(res.msg);
					}
				})
			},
			handleEdit(record) {
				// localStorage.setItem('closeOrderSearch',JSON.stringify(this.$parent.$parent.$parent.queryParam));
				this.$router.push({
					name: 'clothesOrderDetail',
					query: {
						id: record.id
					}
				})
			},
			handleConfirm(record) {
				this.$confirm({
					title: '你确认出厂此订单吗?',
					content: '确认出厂后订单将完成服务',
					onOk: () => clothesConfirm({
						id: record.id
					}).then(res => {
						this.$message.success(res.msg)
						this.handleSearch()
						return res.data
					}).catch(err => err)
				})
			},
			handleRefund(record) {
				this.$confirm({
					title: '你确认要对此订单进行退款吗?',
					content: h => < div style = 'color:red' > 退款后将金额原路返还 < /div>,
					okType: 'danger',
					okText: '退款',
					onOk: () => clothesRefund({
						id: record.id
					}).then(res => {
						this.$message.success(res.msg)
						this.handleSearch()
						return res.data
					}).catch(err => err)
				})
			}
		}
	}
</script>

<style scoped lang="less">
	/deep/ .ant-table-tbody>tr>td {
		&:nth-child(10) {
			padding: 0;
		}

		&:last-child {
			padding: 0;
		}
	}
</style>